import '../css/styles.css';

let userList = [];

// 将需要在 HTML 中调用的函数挂载到 window 对象
window.editUser = editUser;
window.deleteUser = deleteUser;
window.showAddUserPanel = showAddUserPanel;
window.closeUserPanel = closeUserPanel;
window.addUser = addUser;
window.saveUserEdit = saveUserEdit;

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    const user = JSON.parse(localStorage.getItem('user'));
    if (!user || user.role !== 'admin') {
        window.location.href = 'login.html';
        return;
    }
    loadUserList();
});

// 加载用户列表
function loadUserList() {
    fetch(getApiUrl('users'), {
        headers: getHeaders()
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('获取用户列表失败');
        }
        return response.json();
    })
    .then(data => {
        console.log('获取到的用户列表:', data); // 添加调试日志
        userList = data;
        updateUserList();
    })
    .catch(error => {
        console.error('获取用户列表失败:', error);
        showAlert('获取用户列表失败', 'error');
    });
}

// 更新用户列表显示
function updateUserList() {
    const tbody = document.getElementById('userList');
    tbody.innerHTML = '';
    
    userList.forEach(user => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${user.username}</td>
            <td>${user.role}</td>
            <td>${formatDateTime(user.createTime)}</td>
            <td>
                <div class="action-buttons">
                    <button class="edit" onclick="editUser(${user.id})">编辑</button>
                    <button class="delete" onclick="deleteUser(${user.id})">删除</button>
                </div>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

// 显示添加用户面板
function showAddUserPanel() {
    // 创建遮罩层
    const overlay = document.createElement('div');
    overlay.className = 'overlay';
    overlay.addEventListener('click', closeUserPanel);
    document.body.appendChild(overlay);

    // 创建面板
    const panel = document.createElement('div');
    panel.className = 'edit-panel';
    panel.innerHTML = `
        <div class="edit-panel-header">
            <h3>添加新用户</h3>
            <button class="close-button" onclick="closeUserPanel()">&times;</button>
        </div>
        <div class="form-group">
            <label>用户名</label>
            <input type="text" id="username" required>
        </div>
        <div class="form-group">
            <label>密码</label>
            <input type="password" id="password" required>
        </div>
        <div class="form-group">
            <label>角色</label>
            <select id="role" required>
                <option value="admin">管理员</option>
                <option value="user">普通用户</option>
            </select>
        </div>
        <div class="edit-panel-buttons">
            <button class="secondary" onclick="closeUserPanel()">取消</button>
            <button onclick="addUser()">添加</button>
        </div>
    `;

    panel.addEventListener('click', (e) => e.stopPropagation());
    document.body.appendChild(panel);

    requestAnimationFrame(() => {
        overlay.classList.add('active');
        panel.classList.add('active');
    });
}

// 添加用户
async function addUser() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const role = document.getElementById('role').value;

    if (!username || !password) {
        showAlert('请填写必要信息', 'error');
        return;
    }

    try {
        const response = await fetch(getApiUrl('users'), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password, role })
        });

        if (!response.ok) {
            throw new Error('添加用户失败');
        }

        const result = await response.json();
        userList.push(result.user);
        updateUserList();
        showAlert('用���添加成功', 'success');
        closeUserPanel();
    } catch (error) {
        console.error('添加用户错误:', error);
        showAlert('添加用户失败，请重试', 'error');
    }
}

// 删除用户
async function deleteUser(id) {
    if (!confirm('确定要删除这个用户吗？')) {
        return;
    }

    try {
        console.log('正在删除用户:', id); // 添加调试日志
        const response = await fetch(`${config.baseUrl}/users/${id}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        if (!response.ok) {
            const data = await response.json();
            throw new Error(data.message || '删除失败');
        }

        // 从本地列表中移除
        userList = userList.filter(u => u.id !== id);
        updateUserList();
        showAlert('用户删除成功', 'success');
    } catch (error) {
        console.error('删除错误:', error);
        showAlert(error.message || '删除失败，请重试', 'error');
    }
}

// 通用的请求头
function getHeaders() {
    return {
        'Content-Type': 'application/json'
    };
}

// 关闭面板
function closeUserPanel() {
    const overlay = document.querySelector('.overlay');
    const panel = document.querySelector('.edit-panel');
    
    if (overlay && panel) {
        overlay.classList.remove('active');
        panel.classList.remove('active');
        
        setTimeout(() => {
            overlay.remove();
            panel.remove();
        }, 300);
    }
}

// 显示提示
function showAlert(message, type) {
    const alertBox = document.getElementById('alertBox');
    if (!alertBox) return;
    
    alertBox.textContent = message;
    alertBox.className = `alert alert-${type}`;
    alertBox.style.display = 'block';
    
    setTimeout(() => {
        alertBox.style.animation = 'fadeOut 0.5s';
        setTimeout(() => {
            alertBox.style.display = 'none';
            alertBox.style.animation = '';
        }, 500);
    }, 3000);
}

// 格式化日期时间
function formatDateTime(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
}

// 编辑用户
function editUser(id) {
    const user = userList.find(u => u.id === id);
    if (!user) {
        showAlert('用户不存在', 'error');
        return;
    }

    // 创建遮罩层
    const overlay = document.createElement('div');
    overlay.className = 'overlay';
    overlay.addEventListener('click', closeUserPanel);
    document.body.appendChild(overlay);

    // 创建编辑面板
    const panel = document.createElement('div');
    panel.className = 'edit-panel';
    panel.innerHTML = `
        <div class="edit-panel-header">
            <h3>编辑用户</h3>
            <button class="close-button" onclick="closeUserPanel()">&times;</button>
        </div>
        <div class="form-group">
            <label>用户名</label>
            <input type="text" id="editUsername" value="${user.username}" required>
        </div>
        <div class="form-group">
            <label>角色</label>
            <select id="editRole" required>
                <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
                <option value="user" ${user.role === 'user' ? 'selected' : ''}>普通用户</option>
            </select>
        </div>
        <div class="form-group">
            <label>创建时间</label>
            <div class="static-text">${formatDateTime(user.createTime)}</div>
        </div>
        <div class="edit-panel-buttons">
            <button class="secondary" onclick="closeUserPanel()">取消</button>
            <button onclick="saveUserEdit(${user.id})">保存</button>
        </div>
    `;

    panel.addEventListener('click', (e) => e.stopPropagation());
    document.body.appendChild(panel);

    requestAnimationFrame(() => {
        overlay.classList.add('active');
        panel.classList.add('active');
    });
}

// 保存用户编辑
async function saveUserEdit(id) {
    const username = document.getElementById('editUsername').value;
    const role = document.getElementById('editRole').value;

    if (!username) {
        showAlert('请填写用户名', 'error');
        return;
    }

    try {
        console.log('正在更新用户:', id, { username, role }); // 添加调试日志
        const response = await fetch(`${config.baseUrl}/users/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, role })
        });

        if (!response.ok) {
            const data = await response.json();
            throw new Error(data.message || '更新失败');
        }

        const result = await response.json();
        
        // 更新本地列表
        const index = userList.findIndex(u => u.id === id);
        if (index !== -1) {
            userList[index] = result.user;
            updateUserList();
        }

        showAlert('用户信息更新成功', 'success');
        closeUserPanel();
    } catch (error) {
        console.error('更新错误:', error);
        showAlert(error.message || '更新失败，请重试', 'error');
    }
} 